package com.dance.netty.nio.demo;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 使用通道实现文件拷贝
 */
public class FileChannel03 {

    public static void main(String[] args) throws Exception {

        FileInputStream fileInputStream = new FileInputStream("src/main/resources/01.txt");
        FileOutputStream fileOutputStream = new FileOutputStream("src/main/resources/02.txt");

        FileChannel readChannel = fileInputStream.getChannel();
        FileChannel writeChannel = fileOutputStream.getChannel();

        ByteBuffer container = ByteBuffer.allocate(4);

        // 循环读取
        for (;;){

            // 读取之前清空一下上一次的数据缓存
            container.clear();

            // 从通道中读取数据到Channel 返回值为读取数量
            int byteSize = readChannel.read(container);

            System.out.println(byteSize);

            // -1为读取完成 没有读取到任何数据
            if (byteSize == -1)
                break;

            if (byteSize == 3)
                System.out.println("到3了");

            // 读写切换 重置游标
            container.flip();

            // 为了避免写入空格 采用设置limit 限制
//            if(byteSize != container.capacity())
//                container.limit(byteSize);

            // 将Buffer中的数据写入到 Channel 返回值为写入的数量
            int write = writeChannel.write(container);
        }

        writeChannel.close();
        readChannel.close();
        fileOutputStream.close();
        fileInputStream.close();

    }

}
